package com.dq.service.service.impl;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.ServiceAdd;
import com.dq.controller.in.ServiceRecordQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.Vo;
import com.dq.domain.subscribe.Subscribe;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.evaluation.EvaluationRecord;
import com.dq.domain.message.custome.ServiceMessage;
import com.dq.domain.org.Org;
import com.dq.domain.record.ProfitRecord;
import com.dq.domain.record.ServiceRecord;
import com.dq.domain.service.ServiceProject;
import com.dq.domain.service.ServiceProjectRecordCentre;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.dto.OrgStatisticeDto;
import com.dq.repository.BaseRepositories;
import com.dq.repository.evaluation.EvaluationRecordRepository;
import com.dq.repository.service.ServiceProjectRecordCentreRepository;
import com.dq.service.messsge.ServiceMessageService;
import com.dq.service.org.OrgService;
import com.dq.service.service.ServiceRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuhui
 * @date 2019/12/2 0002 15:37:48
 */
@Service
public class ServiceRecordServiceImpl extends BaseRepositories implements ServiceRecordService {

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private ServiceMessageService serviceMessageService;
    @Autowired
    private ServiceProjectRecordCentreRepository serviceProjectRecordCentreRepository;
    @Autowired
    private EvaluationRecordRepository evaluationRecordRepository;
    @Autowired
    private OrgService orgService;

    @Override
    public List<OrgStatisticeDto> projectStatustuce(Long beginTime,Long endTime) {
        String sql = new String("select sr.sys_dept_id as orgId,COUNT(sr.id) as num from service_record sr" +
                "and sr.create_time &gt;=" +beginTime+"and sr.create_time &lt;="+
                " ORDER BY sr.sys_dept_id");
        Query query = entityManager.createNativeQuery(sql);
        List rows = query.getResultList();
        List<OrgStatisticeDto> userOrderCountObjList = new ArrayList<>();
        rows.forEach(o -> {
            Object[] cells = (Object[]) o;
            OrgStatisticeDto userOrderCountObj = new OrgStatisticeDto();
            userOrderCountObj.setOrgId(Long.parseLong(cells[0].toString()));
            userOrderCountObj.setNum(Long.parseLong(cells[1].toString()));
            userOrderCountObjList.add(userOrderCountObj);
        });
        return userOrderCountObjList;
    }

    /**
     *
     * @param subscribe
     * @param serviceAdd
     * @param flag 1为预约提交服务 0为直接到店服务
     */
    @Override
    public void addService(Subscribe subscribe,ServiceAdd serviceAdd,ServiceRecord serviceRecord) {
        if(serviceAdd.getFlag() == 1){
            serviceRecord = saveService(subscribe,serviceAdd,serviceRecord);
        }else {
            serviceRecord = shopService(serviceAdd,serviceRecord);
        }
        saveServiceProjectRecordCentre(serviceRecord,serviceAdd.getServiceProjectId());
    }

    /**
     * 到店服务
     * @param serviceAdd
     * @return
     */
    public ServiceRecord shopService(ServiceAdd serviceAdd,ServiceRecord serviceRecord) {
        serviceRecord.setServiceEndTime(System.currentTimeMillis());
        serviceRecord.setServiceBackAmount(serviceAdd.getServiceBackAmount());
        serviceRecord.setServiceStatus(ServiceRecord.ServiceStatus.confirmed);
        serviceRecord.setProjectCategoryName(serviceAdd.getProjectCategoryName());
        serviceRecord.setProjectName(serviceAdd.getProjectName());
        ServiceRecord save = serviceRecordRepository.save(serviceRecord);

        saveServiceMessage(save);
        return save;
    }

    /**
     * 预约 服务结束 提交服务
     * @param subscribe
     * @param serviceAdd
     * @return
     */
    public ServiceRecord saveService(Subscribe subscribe,ServiceAdd serviceAdd,ServiceRecord serviceRecord){
        serviceRecord.setServiceEndTime(System.currentTimeMillis());
        serviceRecord.setServiceBackAmount(serviceAdd.getServiceBackAmount());
        serviceRecord.setServiceStatus(ServiceRecord.ServiceStatus.confirmed);
        serviceRecord.setSubscribe(subscribe);
        serviceRecord.setProjectCategoryName(serviceAdd.getProjectCategoryName());
        serviceRecord.setProjectName(serviceAdd.getProjectName());
        ServiceRecord save = serviceRecordRepository.save(serviceRecord);

        saveServiceMessage(save);

        return save;
    }

    public void saveServiceMessage(ServiceRecord save) {
        ServiceMessage serviceMessage = new ServiceMessage();
        serviceMessage.setWxuser(save.getWxUser());
        serviceMessage.setServiceRecord(save);
        try {
            serviceMessageService.save(serviceMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveServiceProjectRecordCentre(ServiceRecord serviceRecord,List<Long> serviceProjectId){
        serviceProjectId.forEach(id ->{
            ServiceProjectRecordCentre s = new ServiceProjectRecordCentre();
            s.setServiceRecord(serviceRecord);
            s.setServiceProject(dao.get(ServiceProject.class,id));
            serviceProjectRecordCentreRepository.save(s);
        });
    }

    @Override
    public void addManualPrice(Long id , BigDecimal scoringScale) {
        ServiceRecord serviceRecord = dao.get(ServiceRecord.class,id);
        List<ServiceProjectRecordCentre> list = serviceProjectRecordCentreRepository.findByServiceRecord(serviceRecord);
        BigDecimal sum = BigDecimal.ZERO;
        for (ServiceProjectRecordCentre s:list) {
            if(s.getServiceProject() != null){
                if(s.getServiceProject().getProjectManualPrice() != null) {
                    sum = sum.add(s.getServiceProject().getProjectManualPrice());
                }
            }
        }
        sum = sum.multiply(scoringScale);
        serviceRecord.setManualPrice(sum);
        ServiceRecord save = serviceRecordRepository.save(serviceRecord);
        saveProfitRecord(save);
    }

    @Override
    public Vo list(ServiceRecordQuery serviceRecordQuery)  throws AdminException {
        serviceRecordQuery.format();
        Map<String, Object> query = serviceRecordQuery.parseMap();
        if(StringUtils.isNotEmpty(serviceRecordQuery.getCardNo())){
            query.put("staffUser_cardNo"+ BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(serviceRecordQuery.getCardNo()));
            query.remove("cardNo");
        }
        if(StringUtils.isNotEmpty(serviceRecordQuery.getUserRealName())){
            query.put("staffUser_userRealcName"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(serviceRecordQuery.getUserRealName()));
            query.remove("userRealName");
        }
        if(serviceRecordQuery.getBeginTime()!=null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr,serviceRecordQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(serviceRecordQuery.getEndTime()!=null){
            query.put("createTime"+BaseDaoImpl.lteSqlStr,serviceRecordQuery.getEndTime());
            query.remove("endTime");
        }
        if(serviceRecordQuery.getOrgId()!=null){
            query.put("sysDept_id",serviceRecordQuery.getOrgId());
            query.remove("orgId");
        }else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            if(orgList == null || orgList.size() <= 0) {
                throw new AdminException("此账号无负责门店");
            }
            query.put("sysDept" + BaseDaoImpl.inSqlStr, orgList);
        }
        query.put("serviceStatus", ServiceRecord.ServiceStatus.endService);
        List<ServiceRecord> list =  dao.find(dao.query2Hql(ServiceRecord.class,query),query);
        List<ServiceRecord.PcServiceRecord> records = new ArrayList<>();
        list.forEach(serviceRecord -> {
//            EvaluationRecord record = evaluationRecordRepository.findByServiceRecordAndDeletedFalse(serviceRecord);
            EvaluationRecord record = null;
            Long average = null;
            if(record != null){
                average = record.getAverageScore();
            }
            records.add(serviceRecord.toPcServiceRecord(average));
        });
        Long count = dao.count(dao.count2Hql(ServiceRecord.class,query),query);
        PageHelper.startPage(serviceRecordQuery.getPage(),serviceRecordQuery.getSize());
        PageInfo pageInfo = new PageInfo(records);
        pageInfo.setTotal(count);
        return new Vo(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceRecord delete(Long id) throws AdminException {
        ServiceRecord serviceRecord = dao.get(ServiceRecord.class, id);
        if (null == serviceRecord) {
            throw new AdminException("顾客服务记录不存在");
        }

        serviceRecord.setDeleted(true);
        serviceRecord.setLastModifyTime(System.currentTimeMillis());
        SysUser user = sysUserService.getUser();
        serviceRecord.setUpdateUser(user);

        serviceRecordRepository.save(serviceRecord);

        List<ServiceProjectRecordCentre> serviceProjectRecordCentreList = serviceProjectRecordCentreRepository.findByServiceRecord(serviceRecord);
        for (ServiceProjectRecordCentre serviceProjectRecordCentre : serviceProjectRecordCentreList) {
            serviceProjectRecordCentre.setDeleted(true);
            serviceProjectRecordCentre.setLastModifyTime(System.currentTimeMillis());
            serviceProjectRecordCentre.setUpdateUser(user);

            serviceProjectRecordCentreRepository.save(serviceProjectRecordCentre);
        }

        return serviceRecord;
    }


    public void saveProfitRecord(ServiceRecord s){
        ProfitRecord p = new ProfitRecord();
        p.setUser(s.getWxUser());
        p.setChangeProfitType(ProfitRecord.ChangeProfitType.consume);
        p.setProfitChangeType(ProfitRecord.ProfitChangeType.add);
        p.setChangeNum(s.getServiceBackAmount());
        profitRecordRepository.save(p);
    }


}
